package com.whw.service.impl;

import com.whw.dao.UserDao;
import com.whw.model.User;
import com.whw.service.UserService;
import io.rong.RongCloud;
import io.rong.models.TokenResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by 忘尘无憾 on 2017/07/05.
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;

    @Override
    public User login(String name, String password) {
        return userDao.findByAccountAndPassword(name, password);
    }

    @Override
    public boolean reg(User user) throws Exception {
        //根据用户昵称查找数据库是否有该用户
        if (userDao.findByName(user.getNc()) == null) {
            userDao.save(user);//新增注册用户
            User user1 = userDao.findByName(user.getNc());
            String appKey = "kj7swf8okhjd2";//替换成您的appkey
            String appSecret = "MrIyIM8KZHD";//替换成匹配上面key的secret
            RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
            // 获取 Token 方法
            TokenResult userGetTokenResult = null;
            try {
                String tx = "";
                if (user1.getYhtx() != null) {
                    tx = user1.getYhtx();
                }
                userGetTokenResult = rongCloud.user.getToken(user1.getYhbh(), user1.getNc(), tx);
                System.out.println(user1.getYhbh());
                System.out.println(userGetTokenResult.getToken());
                System.out.println(userGetTokenResult.getCode()+"");
                if (userGetTokenResult.getCode() == 200) {
                    user1.setToken(userGetTokenResult.getToken());
                    userDao.update(user1);
                    return true;
                }
                userDao.delete(user1);
            } catch (Exception e) {
                System.out.print(e.toString());
                return false;
            }
        }
        return false;
    }

    @Override
    public User update(User user) {
        userDao.saveOrUpdate(user);
        return user;
    }

    @Override
    public boolean updatePass(String id, String oldPassword, String newPassword) {
        User user = userDao.findById(id);
        if (login(user.getYhbh(), oldPassword) == null) {
            return false;
        }
        user.setMm(newPassword);
        userDao.saveOrUpdate(user);
        return true;
    }

    @Override
    public User findById(String id) {
        return userDao.findById(id);
    }

    @Override
    public User findByName(String name) {
        return userDao.findByName(name);
    }

    @Override
    public boolean deleteUser(String id) {
        User user = userDao.findById(id);
        if (user != null) {
            userDao.delete(user);
            return true;
        }
        return false;
    }
}
